package com.nowcoder.community.controller.interceptor;

import com.nowcoder.community.annotation.LoginRequired;
import com.nowcoder.community.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**拦截器*/
@Component
public class LoginRequiredInterceptor implements HandlerInterceptor {

    @Autowired
    private HostHolder hostHolder;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {  //拦截到的请求是否是controller里面的 如果不是，就放行，这样预检请求就不会被拦下来，正式的请求也就能请求成功了
            HandlerMethod handlerMethod = (HandlerMethod) handler;   //由于拦截只需要拦截判定方法，不需要拦截其他静态类型，所以这里转型
            Method method = handlerMethod.getMethod();  //获取方法
            LoginRequired loginRequired = method.getAnnotation(LoginRequired.class); //注解不为空啧则代表带有这个注解（LoginRequired.class）,是需要登录访问的方法
            if (loginRequired != null && hostHolder.getUser() == null) {  //当需要登录访问的功能检查到并没有登录时则跳转登录
                response.sendRedirect(request.getContextPath() + "/login");
                return false;
            }
        }
        return true;
    }
}
